// packagBuy/pages/confirmOrder/confirmOrder.js
var configUrl = require('../../../config/config')   //引入配置接口文件
var getuRL = require('../../../utils/util')   //引入配置接口文件
const app=getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    CustomBar: app.globalData.CustomBar,
    statusHeight:app.globalData.StatusBar,
    isIPX:app.globalData.isIPX,
    isIPXBottom:app.globalData.isIPXBottom,
    showSelectServer:false,   //选择配送方式框 默认关闭
    ischeckTab:1,
    isNewAddress:false,  //定金订单是否显示详细地址输入框
    showOtherAddr:false,  //定金选择地址默认选择框
    dAddr:{},  //定金订单 默认其他地址
    addrinfo:'请选择',
    paymentLoading: '',
    optionsType: ''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    if (options.type) {
      this.setData({
        optionsType: options.type
      })
    }
    if(options.buyLine){
      this.setData({
        buyLine:options.buyLine
      })
    }
    wx.setNavigationBarColor({
      frontColor: '#000000',
      backgroundColor: '#ffffff'
    })
    wx.setNavigationBarTitle({
      title: '确认订单',
    })
    if(options.type=="orderOnline"){   //购物订单
      this.getShippingAddress();
      this.setData({
        isShowOrderType:true,
        orderBuyType:options.type,
      })
    }else if(options.type=="deposit"){    //定金订单
      this.getShippingAddress();
      var nearbyShop = wx.getStorageSync('nowBuyDepositShop')
      var skuDeposit=wx.getStorageSync('nowBuyDepositSku')
      var submitUUID=wx.getStorageSync('submitUUID')
      this.setData({
        submitUUID:submitUUID,
        isShowOrderType:false,
        depositNearbyShop:nearbyShop,
        depositSku:skuDeposit,
        depositOderType:true
      })
      var addrs=wx.getStorageSync('temporaryAddressData')
      var addid=wx.getStorageSync('selectAddId')
      if(addrs){  //自选地址
        console.log('自选地址')
        let data=addrs.province+addrs.city+addrs.region+addrs.street
        let province = {code: addrs.provinceCode,name: addrs.province}
        let city = {code: addrs.cityCode,name: addrs.city}
        let region = {code: addrs.regionCode,name: addrs.region}
        let street = {code: addrs.streetCode,name: addrs.street}
        this.getgeocode(data,'1')
        this.setData({
          addrinfo:data,
          sprovince:province,
          scity:city,
          sregion:region,
          sstreetName:street,
          isNewAddress:true,
          showOtherAddr:false,
          depositReceiverName:'',
          depositPhoneNum:'',
          depositAddress:''
        })

      // var addrInfo=addrs.provinceName+addrs.cityName+addrs.regionName+(addrs.streetName?addrs.streetName:'')+addrs.detailAddress
      // this.getgeocode(addrInfo,'1')
      // this.setData({
      //   addrinfo:addrInfo,
      //   addrInfoData:addrs,
      //   depositReceiverName:addrs.name,
      //   depositPhoneNum:addrs.phoneNumber,
      //   isNewAddress:false,
      //   showOtherAddr:false,
      // })
      }else if(addid){   //收货地址列表地址
        console.log('收货地址')
       this.getShippingAddress()
       this.setData({
        isNewAddress:false,
       })
      }else{ //定位地址
        console.log('定位地址')
        var addsd=wx.getStorageSync('addrCode')
        this.setData({
          addrinfo:(addsd.province+addsd.city+addsd.district+ (addsd.townName?addsd.townName:'')),
          sprovince:addsd.province,
          scity:addsd.city,
          sregion:addsd.district,
          sstreetName:addsd.townName,
          depositAddress:addsd.street+addsd.streetNumber,
          isNewAddress:true,
          depositReceiverName:'',
          depositPhoneNum:''
        })
      }
    }else if(options.type=='wholeHouse'){  //全屋购订单
      this.getShippingAddress();
      this.setData({
        orderBuyType:options.type,
        isShowOrderType:true
      })
    }
  },
  getShippingAddress(){   //获取收货地址
    var that=this;
    var parms={ pageFlag:false }
    app.reqFun.requestForm('post',configUrl.addressList,parms,(res)=>{
      if(res.data.success==1){
        if(res.data.data){
          var list=res.data.data.records
            that.setData({
              addressListData:list  //收货地址data
            })
          var isHaveAddress=""
          var selAdr=wx.getStorageSync('selectAddId')
          if(list.length>0){
            for(let val of list){
              if(selAdr){
                if(selAdr==val.id){
                  isHaveAddress=val
                  let addrInfo=val.provinceName+val.cityName+val.regionName+(val.streetName?val.streetName:'')+val.detailAddress
                  that.setData({
                    isHaveAddress:val,
                    addrinfo:addrInfo,
                    addrInfoData:val,
                    depositReceiverName:val.name,
                    depositPhoneNum:val.phoneNumber,
                    isNewAddress:false,
                    showOtherAddr:false,
                  })
                }
              }else if(val.defaultStatus=='Y'){
                isHaveAddress=val
                that.setData({
                  isHaveAddress:isHaveAddress
                })
              }
            }
            if(isHaveAddress==""){
              that.setData({
                isHaveAddress:list[0]
              })
            }
          }else{
            that.setData({
              isHaveAddress:isHaveAddress,
            })
          }
        }else{
          that.setData({
            addressListData:[]  //收货地址data
          })
        }

        var addrCode=wx.getStorageSync('addrCode') //定位地址
        var temporaryAddressData=wx.getStorageSync('temporaryAddressData') //选择地址
        var isHaveAddr=that.data.isHaveAddress //收货地址
        var postAddrCode=''
        if(temporaryAddressData){
          var address=temporaryAddressData.provinceCode+","+temporaryAddressData.cityCode+","+temporaryAddressData.regionCode
          var showaddress=temporaryAddressData
          if(temporaryAddressData.street){
            address+=(","+temporaryAddressData.streetCode)
          }
          if(temporaryAddressData.streetCode){
            postAddrCode=temporaryAddressData.streetCode
          }else{
            postAddrCode=temporaryAddressData.regionCode
          }
          that.setData({
            addrPostdata:address,
            showdata:showaddress
          })
        }else{
          if(isHaveAddr){
            var address=isHaveAddr.province+","+isHaveAddr.city+","+isHaveAddr.region
            var showaddress=isHaveAddr
            if(isHaveAddr.street){
              address+=(","+isHaveAddr.street)
            }
            if(isHaveAddr.street){
              postAddrCode=isHaveAddr.street
            }else{
              postAddrCode=isHaveAddr.region
            }
            postAddrCode=isHaveAddr.region
            that.setData({
              addrPostdata:address,
              showdata:showaddress
            })
          }else{
            // console.log('175',addrCode)
            var address=addrCode.provinceCode+","+addrCode.cityCode+","+addrCode.districtCode
            var showaddress=addrCode
            if(addrCode.townCode){
              postAddrCode=addrCode.districtCode
            }else{
              postAddrCode=addrCode.districtCode

            }

            that.setData({
              addrPostdata:address,
              showdata:showaddress
            })
          }
        }
        //封装订单确认请求参数
        if(this.data.orderBuyType=='orderOnline'){
          var postData=wx.getStorageSync('submitSku')
          var parms={
            products:postData.sku,     //商品集合  [{number:0,skuId:0}]
            addrCode:postAddrCode,     //地址code
            omsOrderType:postData.omsOrderType,    //订单类型  REGULAR=普通订单, HOUSE_PURCHASE=全屋购, STORE_DEPOSIT=到店定金, SECONDS_KILL_DEPOSIT=秒杀定金
            settlementMethod:postData.settlementMethod,   //BUY_NOW=立即购买, SHOPPING_CART=购物车结算, WHOLE_HOUSE_PURCHASE=全屋购结算
          }
          if (postData.groupActivityId) {
            parms.groupActivityId = postData.groupActivityId
            parms.groupId = postData.groupId
          }
          if (postData.cutActivityId) {
            parms.cutActivityId = postData.cutActivityId
            parms.groupId = postData.groupId
          }
          that.getOrderMsg(parms)
        }else if(this.data.orderBuyType=='wholeHouse'){
          var wholeHouseData=wx.getStorageSync('wholeHouseData')
          var spaceProducts=[]
          for(let val of wholeHouseData){
            var json={
              spaceId:val.id,
              products:[]
            }
            for(let spu of val.pmsHouseBuyProductDto){
              for(let sku of spu.skuStock){
                if(sku.isCheck){
                  json.products.push({number:sku.amount,skuId:sku.skuId})
                }
              }
            }
            spaceProducts.push(json)

          }
          var parms={
            spaceProducts:spaceProducts,
            addrCode:postAddrCode,     //地址code
            omsOrderType:'HOUSE_PURCHASE',    //订单类型  REGULAR=普通订单, HOUSE_PURCHASE=全屋购, STORE_DEPOSIT=到店定金, SECONDS_KILL_DEPOSIT=秒杀定金
            settlementMethod:'WHOLE_HOUSE_PURCHASE',   //BUY_NOW=立即购买, SHOPPING_CART=购物车结算, WHOLE_HOUSE_PURCHASE=全屋购结算
          }
          that.getOrderMsg(parms)
        }

      }else{
        wx.showToast({
          title: '查询地址失败：'+res.data.msg,
          icon:'none'
        })
      }
      if(that.data.depositOderType && !that.data.isNewAddress){  //定金订单默认地址
        // var isHaveAddress=that.data.isHaveAddress
        // that.setData({
        //   addrinfo:(isHaveAddress.provinceName+isHaveAddress.cityName+isHaveAddress.regionName+ (isHaveAddress.streetName?isHaveAddress.streetName:'')+isHaveAddress.detailAddress),
        //   isNewAddress:false,
        //   depositReceiverName:isHaveAddress.name,
        //   depositPhoneNum:isHaveAddress.phoneNumber,
        //   addrInfoData:isHaveAddress
        // })
        // console.log("已有地址",isHaveAddress)
      }
    },true)
  },
  slectAddressData(e){   //普通订单  ，切换选择收货地址
    var addr=e.currentTarget.dataset.val   //已选择收货地址

    var endCode=''
    if(addr.street){
      endCode=addr.street
    }else if(addr.region){
      endCode=addr.region
    }
    var formData=this.data.confirmOrderData;
    formData.addrCode=endCode
    this.setData({
      showdata:addr
    })
    // console.log(formData)
    wx.removeStorageSync('temporaryAddressData')
    this.getOrderMsg(formData);
    this.onCloseModel()
  },
  getOrderMsg(parms){   //请求确认订单数据
    var that=this;
    app.reqFun.requestJson('POST',configUrl.confirmOrder,parms,(res)=>{
      if(res.data.success==1){
        if (!res.data.data.canBuy) {
          wx.showToast({
            title: '商品异常，可能超出限购或不在销售区域',
            duration:3000,
            icon:'none'
          })
        }
        that.setData({
          submitUUID:res.data.data.submitUUID,
          confirmData:res.data.data,
          confirmOrderData:parms
        })
        if(res.data.data.coupons && res.data.data.coupons.couponsList){
          if(res.data.data.coupons.couponsList.length>0){
            for(let val of res.data.data.coupons.couponsList){  //匹配已选的优惠券
              if(val.defaultSelected){
                val.isCheck=true
              }
            }
          }
        }
        that.setData({
          confirmData:res.data.data,
          changeCouponType:false,
          submitBtnDis:false
        })
      }else{
        // console.log('失败')
        wx.showToast({
          title: res.data.msg,
          duration:3000,
          icon:'none'
        })
        that.setData({
          confirmData:null,
          confirmOrderData:parms,
          submitBtnDis:true
        })

      }
    })
  },
  selectModel(e){  //打开弹窗
    var that=this
    var type=e.currentTarget.dataset.type
    if(e.currentTarget.dataset.popup=="nearbyStoresBox"){
      if(type=='thenOrder'){
        that.setData({orderTypeIS:'thenOrder'})
        var showdata=that.data.showdata
        // console.log('309:',showdata)
        if(that.data.showdata.name){
          var data=showdata.provinceName+showdata.cityName+showdata.regionName+showdata.streetName+showdata.detailAddress
        }else if(that.data.showdata.province.path){
          var data=showdata.province.name+showdata.city.name+showdata.region.name+showdata.streetName.name
        }else if(that.data.showdata.provinceCode){
          var data=showdata.province+showdata.city+showdata.district+showdata.street
        }
      }else{
        var data=that.data.addrinfo //先获取行政区划地址 若为收货地址则带有详细地址
        if(that.data.isNewAddress){
          data += that.data.depositAddress //非收货地址需手动拼接详细地址
        }
        // console.log('319:',that.data)
      }
      if(data){
        // console.log('322:',data)
        that.getgeocode(data)
      }else{
        wx.showToast({
          title: '请先选择上门服务地址',
          icon:'none'
        })
        return;
      }

    }
    this.setData({
      modelPopup:e.currentTarget.dataset.popup,
    })
  },
  onCloseModel(e){  //关闭弹窗
    this.setData({
      modelPopup:''
    })
  },
  selectServer(e){   //打开选择配送方式
    var arr=[]
    for(let val of e.currentTarget.dataset.data){
      // console.log(val)
      arr.push({
        name:val=='userRaised'?'用户自提':'送货上门并安装',
        value:val
      })
    }
    this.setData({
      showSelectServer:true,
      sleServerData:arr,
      shopId:e.currentTarget.dataset.index
    })

  },
  onCloseServer(){   // 关闭选择框
    this.setData({
      showSelectServer:false
    })
  },
  onSelectServer(e){  //切换配送方式 -请求刷新数据
    var shopId=this.data.shopId
    var isSelect=e.detail
    var json=this.data.confirmOrderData.distributionModeMap||{}
    json[shopId]=isSelect.value;
    var parms=this.data.confirmOrderData
    parms.distributionModeMap= json
    this.getOrderMsg(parms)
  },
  onChangeCoupon(e) {   //切换优惠券TAB
    if(e.currentTarget.dataset.index==1){
      this.setData({
        ischeckTab:1
      })
    }else{
      this.setData({
        ischeckTab:2
      })
    }
  },
  selectThisCoupon(e){   //选择优惠券
    this.setData({
      changeCouponType:true
    })
    var item=e.currentTarget.dataset.item
    var confirmData=this.data.confirmData
    for(let val of confirmData.coupons.couponsList){
      if(val.useType.value==item.useType.value){
        if(val.couponCode==item.couponCode){
          if(val.isCheck){
            val.isCheck=false
          }else{
            val.isCheck=true
          }
        }else{
          val.isCheck=false
        }
      }
      // else if(val.useType.value==item.useType.value){
      //   val.isCheck=false
      //   if(val.couponCode==item.couponCode){
      //     val.isCheck=true
      //   }
      // }

    }
    this.setData({
      confirmData:confirmData
    })
  },
  cofirmBtn(){   //确认选择优惠   ---切换传参待核对
    var parms=this.data.confirmOrderData
    var coupons=this.data.confirmData.coupons.couponsList
    var arr=[]
    for(let val of coupons){
      if(val.isCheck){
        arr.push(val.couponCode)
      }
    }
    parms.couponCodes=arr
    this.getOrderMsg(parms)
    this.onCloseModel()
  },
  RefreshRestore(){   //使用推荐优惠
    var parms=this.data.confirmOrderData
    delete parms['couponCodes']
    this.getOrderMsg(parms)
    this.setData({
      changeCouponType:false
    })
  },
  getLeaving(e){  //留言信息
    var shopName=e.currentTarget.dataset.shopname
    var logsmoth=e.currentTarget.dataset.logsmethod
    var confirmData=this.data.confirmData
    for(let val of confirmData.shopProducts){
      if(val.name==shopName){
        for(let logs of val.logisticsProductRespDtos){
          if(logs.logisticsMethod==logsmoth){
            logs.message=e.detail
          }
        }
      }
    }
  },
  slectAddressData2(e){  //  定金订单 选择已存在地址
      var addr=e.currentTarget.dataset.val
      console.log("定金订单 选择已存在地址", addr)
      var addrInfo=addr.provinceName+addr.cityName+addr.regionName+(addr.streetName?addr.streetName:'')+addr.detailAddress
      this.getgeocode(addrInfo,'1')
      this.setData({
        addrinfo:addrInfo,
        addrInfoData:addr,
        depositReceiverName:addr.name,
        depositPhoneNum:addr.phoneNumber,
        isNewAddress:false,
        showOtherAddr:false,
      })

      this.onCloseModel()
  },
  selectOhterAddr(){  //选择其他收货地址
    this.setData({
      showOtherAddr:true,
      sprovince:'',
      scity:'',
      sregion:'',
      sstreetName:'',
    })
    this.getAddressSelectData()
  },
  AddOhterAddr(){  //去新增地址
    wx.navigateTo({
      url: '../../../packagMy/pages/personal/newAddress/newAddress',
    })
  },
  getAddressSelectData(e,aa){  //查询4级地址数据
    var that=this;
    var parms={parentCode:100000000000}
    var data=""
    if(e){
      if(aa){
        data=e
      }else{
        data=e.currentTarget.dataset.val
      }
      parms.parentCode=data.code
      var dAddr=this.data.dAddr
      if(data.areaLevel==2){
        dAddr.sprovince=data
        that.setData({dAddr:dAddr,sprovince:data})
      }else if(data.areaLevel==3){
        dAddr.scity=data
        that.setData({dAddr:dAddr,scity:data})
      }else if(data.areaLevel==4){
        dAddr.sregion=data
        that.setData({dAddr:dAddr,sregion:data})
      }else if(data.areaLevel==5){
        dAddr.sstreetName=data
        that.setData({dAddr:dAddr,sstreetName:data})
      }
    }
    app.reqFun.requestJson('get',configUrl.listByParentCode,parms,(res)=>{
      if(res.data.success==1){
        if(res.data.data.length>0){
          that.setData({
            itemsAddr: res.data.data,
          })
        }else{
          var newAddrAll=that.data.dAddr
          var addrinfo=newAddrAll.sprovince.name+newAddrAll.scity.name+newAddrAll.sregion.name+newAddrAll.sstreetName.name
          // console.log('511:',addrinfo)

          that.getgeocode(addrinfo,'1')
          that.setData({  //关闭弹窗
            modelPopup:'',
            showOtherAddr:false,
            isNewAddress:true,
            addrinfo:addrinfo,
            depositAddress:''
          })

        }
      }else{
        wx.showToast({
          title: '查询地址失败：'+res.data.msg,
          icon:'none'
        })
      }
    },true)
  },
  restSelect(e){  //重新选择
    if(e.currentTarget.dataset.val==2){
      this.setData({sprovince:'',scity:'',sregion:'',sstreetName:''})
      this.getAddressSelectData()
    }else if(e.currentTarget.dataset.val==3){
      this.setData({scity:'',sregion:'',sstreetName:''})
      this.getAddressSelectData(e.currentTarget.dataset.item,true)
    }else if(e.currentTarget.dataset.val==4){
      this.setData({sregion:'',sstreetName:''})
      this.getAddressSelectData(e.currentTarget.dataset.item,true)
    }
  },
  docMsgNote(e){  //定金留言
    // console.log(e)
    this.setData({
      docMsgNote:e.detail
    })
  },
  depositReceiverName(e){  //定金客户姓名
    // console.log(e)
    this.setData({
      depositReceiverName:e.detail
    })
  },
  depositPhoneNum(e){  //定金手机号
    // console.log(e)
    this.setData({
      depositPhoneNum:e.detail
    })
  },
  depositAddress(e){  //定金详细地址
    this.setData({
      depositAddress:e.detail
    })

  },
  getNearbyStore(e){
    var addrInfo=this.data.addrinfo
    addrInfo+=this.data.depositAddress
    this.getgeocode(addrInfo,1)
  },
  getgeocode(data,type){   //地址获取经纬度
    var that=this;
    var parms={address:data}
    console.log('data', data)
    app.reqFun.requestJson('get',configUrl.geocode,parms,(res)=>{
      if(res.data.success==1){
        that.nearbyShop(res.data.data.latitude,res.data.data.longitude,type)
      }
    })
  },
  nearbyShop(lat,long,type){  //经纬度获取附近门店   distance范围 latitude纬度   longitude 经度
    var that=this;
    var parms={
      distance:100000,
      latitude:lat,
      longitude:long
    }
    app.reqFun.requestJson('get',configUrl.nearbyShop,parms,(res)=>{
      if(res.data.success==1){
        if(res.data.data){
          if(type==1){  //切换服务地址匹配附近门店
            that.setData({
              depositNearbyShop:res.data.data[0]
            })
          }
          that.setData({
            nowShowNearbyList:res.data.data
          })
          if(that.data.orderTypeIS=='thenOrder'){  //用户自提 -- 附近门店回显
            var comfilyData=that.data.confirmData
            for(let val of res.data.data){
              val.isChecked=false
              if(val.code==comfilyData.nearDepotDto.code){
                val.isChecked=true
              }
            }
            that.setData({
              nowShowNearbyList:res.data.data
            })
          }
        }else{
          that.setData({
            nowShowNearbyList:[]
          })
        }
      }else{
        that.setData({
          depositNearbyShop:'',
          nowShowNearbyList:[]
        })
        wx.showToast({
          title: '当前区域暂无门店：'+res.data.msg,
          icon:'none',
          duration:3000
        })
      }
    })
  },
  slectNearby(e){  //定金订单选择预约门店
    if(this.data.orderTypeIS=='thenOrder'){
      var eData=e.currentTarget.dataset.val
      var comfilyData=this.data.confirmData
      var nowShowNearbyList=this.data.nowShowNearbyList
      for(let val of nowShowNearbyList){
        val.isChecked=false
        if(val.code==eData.code){
          val.isChecked=true
        }
      }
      comfilyData.nearDepotDto={
        code: eData.code,
        distance: eData.distance.value,
        depotName: eData.name,
        consultPhone: eData.consultPhone,
        address: eData.address,
      }
      this.setData({
        nowShowNearbyList:nowShowNearbyList,
        confirmData:comfilyData
      })
      var postData=this.data.confirmOrderData
      postData.nearDepotDto=comfilyData.nearDepotDto
      this.getOrderMsg(postData)   //切换提货门店 刷新数据
    }else{
      this.setData({
        depositNearbyShop:e.currentTarget.dataset.val
      })
    }
    this.onCloseModel()
  },
  onClickButton(){    //提交订单
    var showdata=this.data.showdata
    var type=this.data.isShowOrderType   //区分定金订单和商品订单  true=商品订单/全屋购  false=定金订单
    if(type){
      if(!showdata.name){
        wx.showToast({
          title: '请填写完整的收货地址。',
          icon:'none'
        })
        return;
      }
      var confirmData=this.data.confirmData   //返回确认数据
      console.log('confirmData', confirmData)
        var newParms={}    //下单json
        newParms.productCouponAmount=confirmData.productCouponAmount          //商品优惠券金额
        newParms.productTotalAmount=confirmData.productTotalAmount          //商品总额
        newParms.sendPackCouponAmount=confirmData.sendPackCouponAmount          //送装优惠券金额
        newParms.sendPackCoverCharge=confirmData.sendPackCoverCharge         //送装服务费
        newParms.totalAmount=confirmData.totalAmount	                      //合计总金额
        newParms.receiveAddressId=confirmData.umsMemberReceiveAddres.id        //收货地址ID
        newParms.paymentType='SMALL_PROGRAM'                                     //支付方式
        // newParms.omsOrderType='REGULAR'                                     //订单类型
        newParms.omsOrderType=confirmData.omsOrderType                         //订单类型
        newParms.nearDepotDto=confirmData.nearDepotDto                      //附近门店
        newParms.freight=confirmData.freight                            //运费
        newParms.groupActivityId=confirmData.groupActivityId                            //活动id
        newParms.groupId=confirmData.groupId                            //团id
        if(this.data.buyLine=='car'){
          newParms.purchaseWay="shoppingCart"
        }
        var couponArr=[]
        if(confirmData.coupons && confirmData.coupons.couponsList){
          for(let val of confirmData.coupons.couponsList){
            if(val.defaultSelected){
              couponArr.push(val.couponCode)
            }
          }
        }
        newParms.couponCodes=couponArr    //优惠券code集合

        var newGoodsList=[]            //构建子订单集合
        for(let or of confirmData.shopProducts){
          var goodsArr={
            name:or.name,
            shopId:or.shopId,
            productSender:or.productSender,
            createOrderProductDtos:[]
          }
          for(let logs of or.logisticsProductRespDtos){
              var logistcs={
                productSender:logs.productSender,   //发货方
                distributionMode:logs.distributionMode,  //配送方式
                freight:logs.freight,          // 运费
                logisticsMethod:logs.logisticsMethod,    //物流方式
                orderAmount:logs.orderAmount,          //分堆订单金额
                sendPackCoverCharge:logs.sendPackCoverCharge,     //送装费
                message:logs.message,
                products:[],     //商品集合
              }
              for(let sku of logs.productDtos){
                var skuJson={
                  freight:sku.freight,
                  number:sku.number,
                  sendPackCoverCharge:sku.sendPackCoverCharge,
                  skuId:sku.skuId
                }
                logistcs.products.push(skuJson)
              }
              goodsArr.createOrderProductDtos.push(logistcs)
          }
          newGoodsList.push(goodsArr)
        }
        newParms.createOrderItemDtos=newGoodsList                     //子订单赋值

        if(this.data.orderBuyType=='wholeHouse'){  //全屋购订单
          newParms.spaceProducts=this.data.confirmOrderData.spaceProducts
          newParms.omsOrderType='HOUSE_PURCHASE'
          newParms.promotionAmount=confirmData.promotionAmount
        }
        // console.log(newParms)
        /////////////////////////////////////////////////////////
        this.submitOrdinaryOrder(newParms)  //调用生成订单
    }else{  /** 定金订单 */
      var isNewAddress=this.data.isNewAddress
      var skudata=this.data.depositSku
      var nearShop=this.data.depositNearbyShop
      if(!nearShop){
        wx.showToast({
          title: '当前区域暂无门店',
          icon:'none',
          duration:3000
        })
      }
      if(!this.data.depositReceiverName){
        wx.showToast({
          title: '请输入姓名',
          icon:'none',
          duration:3000
        })
        return
      }
      var parms={
        paymentType:'SMALL_PROGRAM',    //支付方式
        omsOrderType:skudata.orderType,    //订单类型
        note:this.data.docMsgNote?this.data.docMsgNote:'',  //留言
        deposit:skudata.showDeposit,   //定金金额
        skuId:skudata.id,        //SKUid
        receiverName:this.data.depositReceiverName?this.data.depositReceiverName:'',   //姓名
        receiverPhone:this.data.depositPhoneNum?this.data.depositPhoneNum:'',   //电话
        nearDepotDto:{
          code:nearShop.code,
          depotName:nearShop.name,
          distance:nearShop.distance.value
        }
      }
      if(isNewAddress){    //地址信息
        if(wx.getStorageSync('temporaryAddressData')){
          this.data.sprovince
          this.data.scity
          this.data.sregion
          this.data.sstreetName
          parms.receiverProvince=this.data.sprovince.code
          parms.receiverProvinceName=this.data.sprovince.name
          parms.receiverCity=this.data.scity.code
          parms.receiverCityName=this.data.scity.name
          parms.receiverRegion=this.data.sregion.code
          parms.receiverRegionName=this.data.sregion.name
          parms.receiverStreet=this.data.sstreetName.code
          parms.receiverStreetName=this.data.sstreetName.name
          parms.receiverDetailAddress=this.data.depositAddress?this.data.depositAddress:''   //详细地址
        }else{
          var addrsd=wx.getStorageSync('addrCode')
          parms.receiverProvince=addrsd.provinceCode
          parms.receiverProvinceName=addrsd.province
          parms.receiverCity=addrsd.cityCode
          parms.receiverCityName=addrsd.city
          parms.receiverRegion=addrsd.districtCode
          parms.receiverRegionName=addrsd.district
          parms.receiverStreet=addrsd.townCode
          parms.receiverStreetName=addrsd.townName
          parms.receiverDetailAddress=this.data.depositAddress
        }

      }else{
        if(this.data.addrInfoData){
          var addr= this.data.addrInfoData
          parms.receiverProvince=addr.province
          parms.receiverProvinceName=addr.provinceName
          parms.receiverCity=addr.city
          parms.receiverCityName=addr.cityName
          parms.receiverRegion=addr.region
          parms.receiverRegionName=addr.regionName
          parms.receiverStreet=addr.street
          parms.receiverStreetName=addr.streetName
          parms.receiverDetailAddress=addr.detailAddress
        }
      }
      // 验证必填
      if(!parms.receiverProvince){
        wx.showToast({
          title: '请选择上门服务地址',
          icon:'none'
        })
        return;
      }
      if(!parms.receiverDetailAddress){
        wx.showToast({
          title: '请填写详细地址',
          icon:'none'
        })
        return;
      }
      if(!parms.receiverPhone){
        wx.showToast({
          title: '请填写联系电话',
          icon:'none'
        })
        return;
      }
      if(!parms.nearDepotDto){
        wx.showToast({
          title: '请选择服务门店',
          icon:'none'
        })
        return;
      }
      this.submitDepositOrder(parms)
    }
  },
  submitOrdinaryOrder(parms){  //提交普通订单生成订单/全屋购订单
    var that=this;
    parms.submitUUID=that.data.submitUUID
    app.reqFun.requestJson('POST',configUrl.createOrder,parms,(res)=>{
      if(res.data.success==1){
        if(!res.data.data.verifyResult){
          let orderType;
          if (parms.omsOrderType === 'SPELL_BUY') {
            orderType = 4
          }
          that.payOrder(res.data.data.orderNo, res.data.data.id, orderType)
          that.setData({submitBtnDis:false})
        }else{

          wx.showToast({
            title: '生成订单失败。',
            icon:'none',
            duration:3000,
          })
          that.setData({ submitBtnDis:true })
        }

      }else{
        wx.showModal({
          title: '提示',
          content: res.data.msg,
          showCancel: false,
          confirmText: '我知道了',
          success (res) {
            if (res.confirm) {
              wx.navigateBack()
            }
          }
        })
      }
    })
  },
  submitDepositOrder(parms){   //提交定金订单-生成订单
    this.setData({
      paymentLoading: 'loading'
    })
    var that=this;
    parms.submitUUID=that.data.submitUUID
    app.reqFun.requestJson('POST',configUrl.createDepositOrder,parms,(res)=>{
      if(res.data.success==1){
        that.payOrder(res.data.data.orderNo, res.data.data.id)
        that.setData({
          paymentLoading: ''
        })
      }else{
        wx.showModal({
          title: '提示',
          content: res.data.msg,
          showCancel: false,
          confirmText: '我知道了',
          success (res) {
            if (res.confirm) {
              wx.navigateBack()
            }
          }
        })
      }
    })
  },
  payOrder(orderNo, orderId, orderType){  //支付订单
    var that=this;
    var parms={
      orderNo:orderNo,
      paymentType:'SMALL_PROGRAM'
    }
    app.reqFun.requestJson('POST',configUrl.payOrder,parms,(res)=>{
      if(res.data.success==1){
        that.setData({
          paymentLoading: ''
        })
        var payData=res.data.data
        that.setData({
          payData:payData
        })
        that.watchPay(payData, orderId, orderType)
      }else{
        app.unPayNotifySubscribe(null, orderId)
        wx.showToast({
          title: '发起支付订单失败',
          icon:'none'
        })
      }
    })
  },
  watchPay(payData, orderId, orderType){
    var that=this;
    wx.requestPayment({
      timeStamp: payData.timeStamp,
      nonceStr: payData.nonceStr,
      package: payData.packageValue,
      signType: payData.signType,
      paySign: payData.paySign,
      success (res) {
        if (that.data.isShowOrderType) {
          app.moreOrderNotifySubscribe(()=>{
            wx.redirectTo({
              url: '/packagBuy/pages/paySuccess/paySuccess?type=success&optionsType='+that.data.optionsType,
            })
          }, orderId, orderType)
        } else {
          app.couponNotifySubscribe(()=>{
            wx.redirectTo({
              url: '/packagBuy/pages/paySuccess/paySuccess?type=success&optionsType='+that.data.optionsType,
            })
          }, orderId)
        }

      },
      fail (res) {
        wx.showModal({
          title: '支付失败',
          content: '支付失败,是否重新支付？',
          success (res) {
            if (res.confirm) {
              that.watchPay(payData, orderId, orderType)
            } else if (res.cancel) {
              app.unPayNotifySubscribe(()=> {
                wx.redirectTo({
                  url: '../paySuccess/paySuccess?type=err&optionsType='+that.data.optionsType,
                })
              }, orderId)
            }
          }
        })
      }
    })
  },
  showModel(e){  //打开附近门店弹窗

  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
      var that=this;
      var parms={ pageFlag:false }
      app.reqFun.requestForm('post',configUrl.addressList,parms,(res)=>{
        if(res.data.success==1){
          if(res.data.data){
            if(res.data.data.records.length>0){
              that.setData({
                addressListData:res.data.data.records
              })
            }
          }else{
            that.setData({
              addressListData:[]
            })
          }
        }else{
          that.setData({
            addressListData:[]
          })
        }
      },true)
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  // onShareAppMessage: function () {

  // }
})
